home *** CD-ROM | disk | FTP | other *** search
/ Java Developer's Companion / Java Developer's Companion.iso / documentation / tutorial / java / threads / example / Clock.java < prev    next >
Encoding:
Java Source  |  1997-07-13  |  1.6 KB  |  49 lines

  1. /*
  2.  * Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved.
  3.  *
  4.  * Permission to use, copy, modify, and distribute this software
  5.  * and its documentation for NON-COMMERCIAL purposes and without
  6.  * fee is hereby granted provided that this copyright notice
  7.  * appears in all copies. Please refer to the file "copyright.html"
  8.  * for further important copyright and licensing information.
  9.  *
  10.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  11.  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  12.  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  13.  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  14.  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  15.  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  16.  */
  17.  
  18. import java.awt.Graphics;
  19. import java.util.Date;
  20.  
  21. public class Clock extends java.applet.Applet implements Runnable {
  22.  
  23.     Thread clockThread = null;
  24.  
  25.     public void start() {
  26.         if (clockThread == null) {
  27.             clockThread = new Thread(this, "Clock");
  28.             clockThread.start();
  29.         }
  30.     }
  31.     public void run() {
  32.         // loop terminates when clockThread is set to null in stop()
  33.         while (Thread.currentThread() == clockThread) {
  34.             repaint();
  35.             try {
  36.                 Thread.sleep(1000);
  37.             } catch (InterruptedException e){
  38.             }
  39.         }
  40.     }
  41.     public void paint(Graphics g) {
  42.         Date now = new Date();
  43.         g.drawString(now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds(), 5, 10);
  44.     }
  45.     public void stop() {
  46.         clockThread = null;
  47.     }
  48. }
  49.